/********************************************
 * 功能说明: ProjectDatasource实体与DTO之间接口数据转换实现
 * 模块名称:
 * 系统名称:
 * 软件版权: Frank
 * 系统版本: 1.0.0.1
 * 开发人员:
 * 开发时间: 2019-12-18 18:41:08
 * 审核人员:
 * 相关文档:
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.uaa.web.converter;

import com.spring.arch.common.converter.AbstractConverter;
import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.uaa.dto.ProjectDatasourceDTO;
import com.spring.arch.uaa.errorcode.UaaErrorCode;
import com.spring.arch.common.converter.AbstractConverter;
import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.uaa.dto.ProjectDatasourceDTO;
import com.spring.arch.uaa.model.ProjectDatasource;
import com.spring.arch.uaa.repository.ProjectDatasourceRepository;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.spring.arch.uaa.errorcode.UaaErrorCode.E2001004001;

/**
 * ProjectDatasource实体与DTO之间接口数据转换实现
 *
 * @author
 * @version 1.0.0.1
 * @since 2019-12-18 18:41:08
 */
@Component
public class WebProjectDatasourceConverter extends AbstractConverter<ProjectDatasource, ProjectDatasourceDTO> {

    @Autowired
    private ProjectDatasourceRepository projectDatasourceRepository;

    @Override
    public ProjectDatasource toModel(@NonNull final ProjectDatasourceDTO dto) {
        if(dto.isNew()) {
            return constructModel(dto);
        } else {
            return updateModel(dto);
        }
    }

    @Override
    public ProjectDatasourceDTO toDTO(@NonNull final ProjectDatasource model) {
        final ProjectDatasourceDTO dto = new ProjectDatasourceDTO();

        dto.setId(model.getId());
        dto.setSchema(model.getSchema());
        dto.setUrl(model.getUrl());
        dto.setUsername(model.getUsername());
        dto.setPassword(model.getPassword());


        this.convertCommonToDTO(model, dto);

        return dto;
    }

    /**
     * 构建新Model
     */
    private ProjectDatasource constructModel(final ProjectDatasourceDTO dto) {
        final ProjectDatasource model = new ProjectDatasource();
        this.dtoToModel(dto, model);
        return model;
    }

    /**
     * 更新Model
     */
    private ProjectDatasource updateModel(final ProjectDatasourceDTO dto) {
        final ProjectDatasource model = this.projectDatasourceRepository.findById(dto.getId())
                .orElseThrow(() -> ExceptionHolder.serviceException(UaaErrorCode.E2001004001,
                        ProjectDatasource.class.getSimpleName()));
        this.dtoToModel(dto, model);
        return model;
    }

    private void dtoToModel(final ProjectDatasourceDTO dto, final ProjectDatasource model) {
        model.setSchema(dto.getSchema());
        //url不设置，根据规则生成更新
        model.setUrl(dto.getUrl());
        model.setUsername(dto.getUsername());
        model.setPassword(dto.getPassword());

    }
}
